#include <stdlib.h>
#include <GL/glut.h>
#include "Particle.hpp"


Particle::Particle()
{
	float shift = RAND_MAX/2;
	MVector3D dir;
	dir.x = (double)rand() - shift;
	dir.y = 0;//(double)rand() - shift;
	dir.z = (double)rand() - shift;

	dir.Normalize();

	int life = (double)rand();

	m_direction = dir;
	m_position  = MVector3D(0.0, 0.0, 10.0);
	m_lifeTime  = (life % 10000)/10000.0 * 1000 + 1500;
	m_velocity  = ((life % 1000)/1000.0 * 0.75 + 0.25)*0.5;
	m_friction  = 0.02;//0.05f;
	m_lastTick = 0;

}

Particle::Particle(MVector3D& dir, MVector3D& pos, float& lifeTime, float& vel, float& friction)
{
	m_direction = dir;
	m_position  = pos;
	m_lifeTime  = lifeTime;
	m_velocity  = vel;
	m_friction  = friction;
}

Particle::Particle(MVector3D dir, MVector3D pos, float lifeTime, float vel, float friction)
{
	m_direction = dir;
	m_position  = pos;
	m_lifeTime  = lifeTime;
	m_velocity  = vel;
	m_friction  = friction;
}

Particle::~Particle()
{
}

void Particle::SetDirection(MVector3D &dir)
{
	m_direction = dir;
}

void Particle::SetLifeTime(float &lifeTime)
{
	m_lifeTime = lifeTime;
}

void Particle::SetVelocity(float &vel)
{
	m_velocity = vel;
}

void Particle::SetFriction(float &friction)
{
	m_friction = friction;
}

void Particle::Update(clock_t tick)
{
	m_lifeTime -= tick;//(tick - m_lastTick);

	m_position = m_position + (m_direction * m_velocity * (tick/100.0));//((tick - m_lastTick)/100.0));

	if(m_velocity > 0.0)
		m_velocity -= (m_friction * (tick/1000.0));//((tick-m_lastTick)/1000.0));
	else
		m_velocity = 0.0;
/*	m_friction -=  0.05 * ((tick - m_lastTick)/1000.0);
	if(m_friction < 0.1)
		m_friction = 0.1;*/
	m_lastTick = tick;
}
bool Particle::IsParticleDead()
{
	if(m_lifeTime < 0)
		return true;

	return false;
}

void Particle::Render()
{
	glPushMatrix();

	glTranslatef(m_position.x, m_position.y, m_position.z);

	glBegin(GL_QUADS);

	//! left-top
	glTexCoord2f(0.0, 1.0);
	glVertex3f(-0.25,
		       0.0,
			   0.25);

	//! left-bottom
	glTexCoord2f(0.0, 0.0);
	glVertex3f(-0.25,
		       0.0,
			   -0.25);

	//! right-bottom
	glTexCoord2f(1.0, 0.0);
	glVertex3f(0.25,
		       0.0,
			   -0.25);

	//! right-top
	glTexCoord2f(1.0, 1.0);
	glVertex3f(0.25,
		       0.0,
			   0.25);

	glEnd();

	glPopMatrix();
}